package controllers

import config.{Global, MyFile}
import play.api.data.Form
import play.api.data.Forms._
import play.api.libs.json.Json
import play.api.mvc.{AbstractController, ControllerComponents}

import javax.inject.Inject
import scala.io.Source

class QtlController @Inject()(cc: ControllerComponents) extends AbstractController(cc) with MyFile {

  def qtlInfoPage = Action { implicit request =>
    Ok(views.html.qtl.qtlInfoPage())
  }

  def qtlPage = Action { implicit request =>
    Ok(views.html.qtl.qtlPage())
  }

  case class QtlData(chr: String, start: Int, end: Int)

  val QtlForm = Form {
    mapping(
      "chr" -> text,
      "start" -> number,
      "end" -> number
    )(QtlData.apply)(QtlData.unapply)
  }

  def getQtlResult = Action { implicit request =>
    val data = QtlForm.bindFromRequest.get
    val index = s"${Global.path}/config/qtl_chr_index/${data.chr}.txt".toFile
    if (index.exists()) {
      val indexs = index.readLines.map(_.toInt).zipWithIndex.filter(x => x._1 >= data.start && x._1 <= data.end).map(_._2)
      val qtlFile = s"${Global.path}/config/qtl_chr/${data.chr}.txt".toFile.readLines

      if (indexs.nonEmpty) {
        val qtl = qtlFile.slice(indexs.min, indexs.max + 1).map { x =>
          x.split("\t").zipWithIndex.map { y => y._2.toString -> y._1 }.toMap
        }
        Ok(Json.obj("qtl" -> qtl.toSeq))
      } else {
        Ok(Json.obj("valid" -> "false"))
      }

    } else {
      Ok(Json.obj("valid" -> "false"))
    }
  }

  def ssrPage = Action { implicit request =>
    Ok(views.html.qtl.ssrPage())
  }

  def getSsrData = Action { implicit request =>

    val ssr1 = s"${Global.path}/config/ssr/ssr1.txt".readLines.map(_.split("\t")).map{x=>
      x.zipWithIndex.map{y=>
        y._2.toString -> y._1
      }.toMap
    }

    val ssr2 = s"${Global.path}/config/ssr/ssr2.txt".readLines.map(_.split("\t")).map{x=>
      x.zipWithIndex.map{y=>
        y._2.toString -> y._1
      }.toMap
    }
    val ssr3 = s"${Global.path}/config/ssr/ssr3.txt".readLines.map(_.split("\t")).map{x=>
      x.zipWithIndex.map{y=>
        y._2.toString -> y._1
      }.toMap
    }
    val ssr4 = s"${Global.path}/config/ssr/ssr4.txt".readLines.map(_.split("\t")).map{x=>
      x.zipWithIndex.map{y=>
        y._2.toString -> y._1
      }.toMap
    }
    Ok(Json.obj("ssr1" -> ssr1,"ssr2" -> ssr2,"ssr3" -> ssr3,"ssr4" -> ssr4))
  }

  def snpPage = Action { implicit request =>
    Ok(views.html.qtl.snpPage())
  }

  def getSnpData = Action { implicit request =>

    val ssr4 = s"${Global.path}/config/ssr/ssr4.txt".readLines.map(_.split("\t")).map{x=>
      x.zipWithIndex.map{y=>
        y._2.toString -> y._1
      }.toMap
    }
    Ok(Json.obj( "ssr4" -> ssr4))
  }

}
